import { useDpSchema, useProps } from '@ray-js/panel-sdk';
import { useSwitchInfo } from './useSwitchInfo';
import { groupBy, sortBy } from 'lodash-es';
import { useSelector } from 'react-redux';
import { ReduxState } from '@/redux';

type SwitchInfo = ReturnType<typeof useSwitchInfo>[0];

export interface GroupedSwitchInfo {
  battery: number;
  name: string;
  groupId: string;
  group: number;
  water: SwitchInfo & { hide?: boolean, isOffLine?: boolean };
  drug: SwitchInfo & { hide?: boolean, isOffLine?: boolean };
  hide: boolean;
  isOffLine: boolean;
}

const getBitValue = (num, idx) => (num & (1 << idx)) >> idx;

export const useWaterControlInfo = (): GroupedSwitchInfo[] => {
  const switchInfo = useSwitchInfo();

  const props = useProps();

  const schema = useDpSchema();

  const getFaultStrings = (faultValue: number) => {
    if (!faultValue) return [];

    const label = schema?.fault?.property.label || [];
    const values = [];
    for (let i = 0; i < label.length; i++) {
      const value = label[i];
      const isExist = getBitValue(faultValue, i);
      if (isExist) {
        values.push(value);
      }
    }
    return values;
  };

  const msg = getFaultStrings(props['fault']);

  const { groupNames } = useSelector((state: ReduxState) => state?.cloudState);

  const groupedSwitchInfo = groupBy(switchInfo, 'group');

  const device_num = props['device_num']?.length === 2 ? props['device_num'] : '1f';

  const deviceNum = parseInt(device_num, 16).toString(2).padStart(5, '0').split('').reverse();

  const sortedGroupedSwitchInfo = deviceNum.map((item, index) => {
    return {
      battery: props[`battery_percentage${index + 1}`],
      groupName: groupNames[`group_${index + 1}`],
      data: groupedSwitchInfo[index + 1] || [],
      groupId: `group_${index + 1}`,
      group: index + 1,
      hide: item === '0',
      isOffLine: msg?.includes?.(`off_line${index + 1}`),
    };
  });

  const deviceInfoByGroup = sortedGroupedSwitchInfo.map(item => {
    return {
      battery: item.battery as number,
      name: item.groupName,
      groupId: item.groupId,
      group: item.group,
      hide: item.hide,
      isOffLine: item.isOffLine,
      water: {
        ...item.data.find(device => device.type === 'water'),
        hide: item.hide,
        isOffLine: item.isOffLine,
      } as SwitchInfo & { hide: boolean, isOffLine: boolean },
      drug: {
        ...item.data.find(device => device.type === 'drug'),
        hide: item.hide,
        isOffLine: item.isOffLine,
      } as SwitchInfo & { hide: boolean, isOffLine: boolean },
    };
  });
  console.log('🚀 ~ useWaterControlInfo ~ deviceInfoByGroup:', deviceInfoByGroup);

  return deviceInfoByGroup;
};
